package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       /*
         1：设置请求参数的编码
         2:解析表单中的数据
         3:beanutils封装成一个javabean
         4：将数据传递给service
         5：接收返回值
           true  打印成功
           false  打印失败
        */
       //   1：设置请求参数的编码
        request.setCharacterEncoding("utf-8");
        //  2:解析表单中的数据
        Map<String, String[]> map = request.getParameterMap();

        User user = new User();
        System.out.println("封装之前user:"+user);
        //3:beanutils封装成一个javabean
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println("封装之后user:"+user);

        //4:将数据传递给service
        UserService userService = new UserServiceImpl();

        boolean register = userService.register(user);

        //设置响应编码
        response.setContentType("text/html;charset=utf-8");

        //判断结构
        if(register){
//            response.getWriter().write("注册成功");
            //注册成功 跳转到登录页面
            response.sendRedirect("/login&register/login.jsp");
        }else{
//            response.getWriter().write("注册失败");
            response.sendRedirect("/login&register/registerError.html");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
